vec2 fixuv(in vec2 uv) {
    vec2 p = 10. * vec2(uv.x / iResolution.x * (iResolution.x / iResolution.y), abs(uv.y / iResolution.y - 1.));
    return p;
}

vec3 drawGrid(in vec2 p) {
    float f = floor(p.x) + floor(p.y);
    vec3 col = mix(vec3(0.75), vec3(0.3), smoothstep(0., 1., mod(f, 2.)));
    return col;
}

// 画中心线
vec3 drawCenterLine(in vec2 p, in vec3 col) {
    p = (2.0 * p - iResolution.xy) / min(iResolution.x, iResolution.y);
    col = mix(col, vec3(1., 0., 0.), smoothstep(abs(p.x), abs(p.x), fwidth(p.x) * 2.));
    col = mix(col, vec3(0., 0., 1.), smoothstep(abs(p.y), abs(p.y), fwidth(p.y) * 2.));
    return col;
}

vec3 fillRect(in vec2 p, in vec4 rect, in vec3 color, in vec3 col) {

    if(p.x >= rect.x && p.x <= rect.x + rect.z && p.y >= rect.y && p.y <= rect.y + rect.w) {
        col = color;
    }
    return col;
}

vec3 drawRect(in vec2 p, in vec4 rect, in vec3 color, in vec3 col) {

    vec2 lt = rect.xy;
    vec2 rt = vec2(rect.x + rect.z, rect.y);
    vec2 lb = vec2(rect.x, rect.y + rect.w);
    vec2 rb = vec2(rect.x + rect.z, rect.y + rect.w);

    float w = fwidth(p.x) * 10./2.;

    vec2[] vs = vec2[](lt, rt, rb, lb);
   
    for(int i = 0, j = 3; i < 4; j = i, i++) {
        vec2 v1 = vs[j] - vs[i];
        vec2 v2 = vs[i] - vs[j];
        vec2 a1 = p - vs[i];
        vec2 a2 = p - vs[j];
        if(dot(v1, a1) > 0. && dot(v2, a2) > 0.) {
            float theta = dot(v1, a1) / dot(v1, v1);
            //计算底边长度
            float bl = length(v1 * theta);
            //邻边长度
            float d = sqrt(pow(length(a1), 2.) - pow(bl, 2.));
            col = mix(col, color, step(d, w*10.10));
        }
    }

    return col;
}

vec3 drawCircle(in vec2 p, in vec2 pos, in float r, in vec3 color, in vec3 col) {

    col = mix(col, color, smoothstep(r, r * 0.99, length(p - pos)));
    return col;
}

vec3 drawCircle(in vec2 p, in vec3 col) {

    float w = 1.0 / iResolution.y;
    vec2 uv = p / iResolution.xy;
    uv -= 0.5;
    uv.x *= iResolution.x / iResolution.t;
    uv.x = abs(uv.x);
    uv.y *= 1.2;
    uv.y -= uv.x * sqrt(((10.0 - uv.x * 15.0) / 20.));
    float r = 0.1 + sin(iTime) * 0.05 + 0.05;
    float d = length(uv) - r;
    float c = smoothstep(w, -w, d);
    col = mix(col, vec3(1., 0., 0.), c);

    return col;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = fixuv(fragCoord);
    float w = fwidth(p.x);
    vec3 col = drawGrid(p);
    col = drawCenterLine(fragCoord, col);
    col = drawCircle(p, vec2(5., 5.), w * 100., vec3(1.), col);
    col = drawRect(p, vec4(1., 1., 2., 2.), vec3(0.3, 0.5, 0.2), col);
    col = drawCircle(fragCoord, col);

    // drawRect(p,vec2)
    fragColor = vec4(col, 1.);
}
